import React, { useState, useMemo, useEffect } from 'react';
import { Common } from 'UtilsCommon';
import Base from './base';
import styles from '../styles/view.scss';

const initEditor = (obj, property) => {
    const { config } = property;
    obj.UEditor = window.UE.getEditor(obj.id, config || {});

    obj.UEditor.ready(() => {
        obj.isInit = true;
        obj.UEditor.setContent(obj.value);
    });
};

const getContent = (obj) => {
    return obj.UEditor && obj.isInit ? obj.UEditor.getContent() : '';
};
const setContent = (obj, value) => {
    value = Common.isNullOrEmpty(value) ? "" : value;
    obj.value = value;
    if (obj.isInit && obj.UEditor) obj.UEditor.setContent(value);
};

const setDisabled = (obj, disabled) => {
    if (!obj.UEditor) return;
    if (disabled) obj.UEditor.setDisabled();
    else obj.UEditor.setEnabled();
};

export default (props) => {
    const { property } = Base.getProps(props);
    const [isVisible, setIsVisible] = useState(property.isVisible !== false);
    const obj = useMemo(() => ({ id: Common.createGuid() }), []);
    const [value, setValue] = useState(Base.getInitValue(property, obj));

    useEffect(() => {
        initEditor(obj, property);
    }, [obj, property]);

    useEffect(() => {
        return () => { try { window.UE.delEditor(obj.id); } catch (err) { } };
    }, [obj]);

    useEffect(() => {
        setContent(obj, value);
    }, [obj, value]);

    property.setIsVisible = (v) => setIsVisible(v);
    property.setValue = (v) => setValue(v);
    property.getValue = () => getContent(obj);
    property.setDisabled = (v) => setDisabled(obj, v);
    property.setIsReadOnly = (v) => setDisabled(obj, v);

    if (!isVisible) return null;

    const className = Base.getClassName(property, styles);
    const { label, isNullable } = property;

    return (
        <div className={className}>
            {label && <div className={styles.divLabel}>
                {isNullable === false && <span style={{ color: 'red', marginRight: 5 }}>*</span>}
                <span>{label}</span></div>}
            <div className={styles.divContent} id={obj.id} name="content" type="text/plain" style={property.style}></div>
        </div>
    );
};